package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
    @Scheduled(cron = "0 * * * * ? ")//每分钟执行一次
    public void autoCancelOrder() {
        log.info("定时任务启动");
        //查询状态为待付款的订单，判断是否超时（当前时间 - 下单时间 > 15分钟），若超时则取消该订单
        List<Orders> byStatusAndOrderTimeLT = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, LocalDateTime.now().plusMinutes(-15));
        if (byStatusAndOrderTimeLT != null && byStatusAndOrderTimeLT.size() > 0) {
            for (Orders orders : byStatusAndOrderTimeLT) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，取消订单");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
        log.info("定时任务结束");
    }

    /*
    * 自动完成订单
    * */
    @Scheduled(cron = "0 0 1 * * ? ")//每天凌晨1点执行
    public void autoConfirmOrder() {
        log.info("定时处理派送中的订单任务启动");
        List<Orders> byStatusAndOrderTimeLT = orderMapper.getByStatusAndOrderTimeLT(Orders.CONFIRMED, LocalDateTime.now().plusHours(-1));
        if (byStatusAndOrderTimeLT != null && byStatusAndOrderTimeLT.size() > 0) {
            for (Orders orders : byStatusAndOrderTimeLT) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
        log.info("定时任务结束");
    }
}
